/**
 * TODO 后期改成TS的方式 , 目前都是将个别的耗时函数放在worker中。后期改成从类中直接调用
 * 需要worker计算的纯函数
 */
import BigNumber from "bignumber.js";

/**
 * 千分位格式化
 */
export const formatNumberToThousand = (num) => {
  let res = num.toString().replace(/\d+/, function (n) {
    // 先提取整数部分
    return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
      return $1 + ",";
    });
  });
  return res;
};

/**
 * 根据坐标，获取复合表头信息（性能高）On
 */
export const getHeaderByCellPos = (coords, computedLevelData) => {
  let { row, col } = coords;
  //点击的是表头表头数据
  if (row < 0) {
    const treeHeaderRowIndex = row + computedLevelData.length;
    return computedLevelData[treeHeaderRowIndex][col];
  } else {
    row = row >= 0 ? -1 : row;
    // 兼容单元格方式点击,因为单元格的点击方式不知道当前是-2行, 所以采用逐个尝试
    for (let i = 0; i < computedLevelData.length; i++) {
      const treeHeaderRowIndex = row - i + computedLevelData.length;
      const result = computedLevelData[treeHeaderRowIndex][col];
      if (result && result.label !== "null") {
        return result;
      }
    }
  }
  return null;
};

/**
 * 统计函数
 */
const statisticsByRange = (params) => {
  const { headerColumn, rangeData } = params;
  let sum = 0;
  let count = 0;
  for (let i = 0; i < rangeData.length; i++) {
    const range = rangeData[i]; //range
    for (let j = 0; j < range.length; j++) {
      const rowData = range[j]; //row
      for (let k = 0; k < rowData.length; k++) {
        const type = headerColumn[k]?.config?.type;
        let cell = rowData[k]; //cell
        if (
          (!isNaN(parseFloat(cell)) && isFinite(cell)) ||
          typeof cell === "number"
        ) {
          cell = parseFloat(cell);
          sum += cell;
          count++;
        }
        if (cell === null || (type !== "text" && cell === "")) {
          cell = 0;
          count++;
        }
      }
    }
  }

  const fix_sum = new BigNumber(sum);

  sum = parseFloat(fix_sum.toFixed(2));
  let avg = 0;
  if (count === 0) {
    avg = 0;
  } else {
    const fix_sum_count = new BigNumber(sum / count);
    avg = parseFloat(fix_sum_count.toFixed(2));
  }

  return {
    statistics: {
      sum: formatNumberToThousand(sum),
      avg: formatNumberToThousand(avg),
      count,
    },
  };
};

/**
 * 工具条根据单元格状态更新状态
 */
export const getToolBarStateData = function (params) {
  const { coords, computedLevelData } = params;
  const userClickedHeaderMeta = getHeaderByCellPos(coords, computedLevelData);
  return {
    userClickedHeaderMeta,
  };
};

function initWorker() {
  /**
   * 注册worker函数
   * @type {function(*): {statistics: {avg: *, count: number, sum: *}}}
   */
  // eslint-disable-next-line no-restricted-globals
  self.statisticsByRange = statisticsByRange;
  // eslint-disable-next-line no-restricted-globals
  self.getToolBarStateData = getToolBarStateData;

  /**
   * 调度worker函数
   */
  // eslint-disable-next-line no-restricted-globals
  self.addEventListener("message", (event) => {
    const { funName, params } = event.data;
    // eslint-disable-next-line no-restricted-globals
    const result = self[funName](params);

    console.log("worker has got");
    console.log(event.data);
    /**数据处理*/
    // eslint-disable-next-line no-restricted-globals
    self.postMessage({
      state: "success",
      code: 200,
      data: result,
    });
  });
}
initWorker();
export default initWorker;
